package net.wenku8.reader.view.online

import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.BookApi
import net.wenku8.reader.api.bookCaseAsPreview
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.enums.KeyOnlineOpenHis
import net.wenku8.reader.model.book.BookPreviewInfo
import net.wenku8.reader.state.StateLogin
import net.wenku8.reader.state.StateReadOnline
import net.wenku8.reader.view.common.BaseViewModel
import java.util.stream.Collectors

class OnlineBookcaseViewModel : BaseViewModel() {

    val bookList = mutableStateListOf<BookPreviewInfo>()

    fun initData() {
        if (!StateLogin.status.value){
            bookList.clear()
            return
        }
        if (bookList.isNotEmpty() && !StateReadOnline.bookCaseRefresh.value){
            return
        }
        loadBookcase()
        StateReadOnline.bookCaseRefresh.value = false
    }

    fun loadBookcase(){
        dataLoading.value = true
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.getBookCase()
            if (ApiResult.isSuccess(apiResult)){
                val list = bookCaseAsPreview(apiResult.data)
                bookList.clear()
                val hisData = MMKV.defaultMMKV().decodeString(KeyOnlineOpenHis, null)
                if(hisData != null){
                    val json = JSON.parseObject(hisData)
                    list.sortByDescending { json.getLongValue(it.bookId, 0) }
                }
                bookList.addAll(list)
                val idList = list.stream().map(BookPreviewInfo::bookId).collect(Collectors.toList())
                val bookCaseList = ArrayList<String>()
                apiResult.data?.forEach{
                    bookCaseList.add(it.bookId)
                }
                StateReadOnline.bookCaseList.value = idList
            }
            dataLoading.value = false
        }
    }

}